import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_slidable/flutter_slidable.dart';

import '../../../provide/riverpod_provider.dart';
import '../../../service/home.api.dart';
import '../../../widget/price_Widget/index.dart';

class ShoppingCartModule extends ConsumerStatefulWidget {
  final AsyncValue shoppingCartData;

  const ShoppingCartModule({super.key, required this.shoppingCartData});

  @override
  _ShoppingCartModuleState createState() => _ShoppingCartModuleState();
}

class _ShoppingCartModuleState extends ConsumerState<ShoppingCartModule> {
  /// dropdown value
  String? _dropdownContentValue = "zxc";

  GlobalKey getGlobalKey(id) {
    GlobalKey slideKey = GlobalKey(debugLabel: '$id');
    return slideKey;
  }

  /// DELETE SHOPPING CART
  void deleteShoppingCart(ids, id) async {
    await DeleteShoppingCartApi.deleteShoppingCartFetch(ids);
    ref.read(shoppingCartIsSelectProvide.notifier).deleteShoppingCart(id);
    Navigator.of(context).pop();
  }

  /// UPDATE SHOPPING CART STATE
  void updateShoppingCartState(value) async {
    await ChangeShoppingCartApi.changeShoppingCartFetch(value);
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      children: [
        Builder(
          builder: (context) {
            if (widget.shoppingCartData.isLoading) {
              return const Text("數據加載中");
            } else if (widget.shoppingCartData.hasError) {
              final errorMessage = widget.shoppingCartData.error.toString();
              if (errorMessage.contains('unauthorized') || errorMessage.contains('401')) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 40),
                  child: TextButton(
                    onPressed: () {
                      Beamer.of(context).beamToNamed('/login');
                    },
                    child: Container(
                      width: 100,
                      height: 40,
                      decoration: const BoxDecoration(color: Colors.teal),
                      child: const Center(
                        child: Text(
                          "去登陸",
                          style: TextStyle(fontSize: 16, color: Colors.white),
                        ),
                      ),
                    ),
                  ),
                );
              } else {
                return const Text("數據錯誤, 請稍後再試");
              }
            } else if (widget.shoppingCartData.value != null && widget.shoppingCartData.value!.valids.isNotEmpty) {
              final shoppingCartIsSelectedCopy = ref.watch(shoppingCartIsSelectProvide);
              return ListView.separated(
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                itemCount: shoppingCartIsSelectedCopy.length,
                itemBuilder: (context, index) {
                  return Slidable(
                    // Specify a key if the Slidable is dismissible.
                    key: getGlobalKey(shoppingCartIsSelectedCopy[index].id),
                    // The start action pane is the one at the left or the top side.
                    startActionPane: ActionPane(
                      // A motion is a widget used to control how the pane animates.
                      motion: const ScrollMotion(),
                      // A pane can dismiss the Slidable.
                      dismissible: DismissiblePane(onDismissed: () {
                        // 直接滑動刪除的回調
                      }),
                      // All actions are defined in the children parameter.
                      children: [
                        // A SlidableAction can have an icon and/or a label.
                        SlidableAction(
                          onPressed: (BuildContext context) {
                            showGeneralDialog(
                              context: context,
                              barrierDismissible: true,
                              // 點擊背景關閉對話框
                              barrierLabel: '',
                              // 對話框的語義化, 必穿, 無内容可穿空字符串
                              transitionDuration: const Duration(milliseconds: 200),
                              pageBuilder:
                                  (BuildContext context, Animation<double> animation, Animation<double> seconde) {
                                return GestureDetector(
                                  onTap: () {},
                                  child: Material(
                                    type: MaterialType.transparency,
                                    child: Center(
                                      child: Container(
                                        width: 300.0,
                                        height: 200,
                                        decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius: BorderRadius.circular(10),
                                        ),
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.center,
                                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                                          children: [
                                            const Text(
                                              "確定刪除該商品",
                                              style: TextStyle(
                                                fontSize: 18,
                                                color: Colors.black,
                                              ),
                                            ),
                                            Row(
                                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                                              children: [
                                                TextButton(
                                                  onPressed: () {
                                                    Navigator.of(context).pop();
                                                  },
                                                  style: ButtonStyle(
                                                    backgroundColor: WidgetStateProperty.all<Color>(Colors.white),
                                                    foregroundColor: WidgetStateProperty.all<Color>(Colors.grey),
                                                    side: WidgetStateProperty.all<BorderSide>(
                                                      const BorderSide(
                                                        color: Colors.grey,
                                                        width: 1.0,
                                                      ),
                                                    ),
                                                    padding: WidgetStateProperty.all<EdgeInsetsGeometry>(
                                                      const EdgeInsets.symmetric(
                                                        horizontal: 10.0,
                                                        vertical: 6.0,
                                                      ),
                                                    ),
                                                  ),
                                                  child: const Text("取消"),
                                                ),
                                                TextButton(
                                                  onPressed: () {
                                                    deleteShoppingCart(
                                                      shoppingCartIsSelectedCopy[index].skuId,
                                                      shoppingCartIsSelectedCopy[index].id,
                                                    );
                                                  },
                                                  style: ButtonStyle(
                                                    backgroundColor: WidgetStateProperty.all<Color>(Colors.teal),
                                                    foregroundColor: WidgetStateProperty.all<Color>(Colors.white),
                                                    padding: WidgetStateProperty.all<EdgeInsetsGeometry>(
                                                      const EdgeInsets.symmetric(
                                                        horizontal: 10.0,
                                                        vertical: 6.0,
                                                      ),
                                                    ),
                                                  ),
                                                  child: const Text("確定"),
                                                )
                                              ],
                                            )
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              },
                            );
                          },
                          backgroundColor: const Color(0xFFFE4A49),
                          foregroundColor: Colors.white,
                          icon: Icons.delete,
                          label: 'Delete',
                        ),
                        SlidableAction(
                          onPressed: (BuildContext context) {},
                          backgroundColor: const Color(0xFF21B7CA),
                          foregroundColor: Colors.white,
                          icon: Icons.share,
                          label: 'Share',
                        ),
                      ],
                    ),

                    // The end action pane is the one at the right or the bottom side.
                    endActionPane: ActionPane(
                      motion: const ScrollMotion(),
                      children: [
                        SlidableAction(
                          // An action can be bigger than the others.
                          flex: 2,
                          onPressed: (BuildContext context) {},
                          backgroundColor: const Color(0xFF7BC043),
                          foregroundColor: Colors.white,
                          icon: Icons.archive,
                          label: 'Archive',
                        ),
                        SlidableAction(
                          onPressed: (BuildContext context) {},
                          backgroundColor: const Color(0xFF0392CF),
                          foregroundColor: Colors.white,
                          icon: Icons.save,
                          label: 'Save',
                        ),
                      ],
                    ),

                    // The child of the Slidable is what the user sees when the
                    // component is not dragged.
                    child: Container(
                      padding: const EdgeInsets.only(top: 10.0, bottom: 10.0, right: 10),
                      width: double.infinity,
                      height: 140,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Row(
                        children: [
                          Consumer(
                            builder: (context, ref, _) {
                              return Checkbox(
                                value: shoppingCartIsSelectedCopy[index].selected,
                                onChanged: (value) {
                                  updateShoppingCartState({
                                    "selected": !shoppingCartIsSelectedCopy[index].selected,
                                    "count": shoppingCartIsSelectedCopy[index].count,
                                    "id": shoppingCartIsSelectedCopy[index].skuId
                                  });
                                  ref.read(shoppingCartIsSelectProvide.notifier).updateShoppingCartIsSelected(
                                        shoppingCartIsSelectedCopy[index].id,
                                      );
                                },
                              );
                            },
                          ),
                          const SizedBox(width: 12),
                          Image.network(
                            shoppingCartIsSelectedCopy[index].picture,
                            width: 120,
                            height: 120,
                            fit: BoxFit.fill,
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            flex: 1,
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  shoppingCartIsSelectedCopy[index].name,
                                  style: const TextStyle(fontSize: 16),
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                SizedBox(
                                  width: 100,
                                  child: DropdownButton(
                                    value: shoppingCartIsSelectedCopy[index].specs[0].valueName,
                                    elevation: 1,
                                    padding: const EdgeInsets.all(0),
                                    menuWidth: 100,
                                    alignment: AlignmentDirectional.center,
                                    isExpanded: true,
                                    style: const TextStyle(
                                      fontSize: 12,
                                      color: Colors.grey,
                                    ),
                                    items: shoppingCartIsSelectedCopy[index].specs.map((value) {
                                      return DropdownMenuItem(
                                        value: value.valueName,
                                        child: Text(value.valueName),
                                      );
                                    }).toList(),
                                    onChanged: (value) {
                                      setState(() {
                                        _dropdownContentValue = value!;
                                      });
                                    },
                                  ),
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    PriceWidget(price: shoppingCartIsSelectedCopy[index].price),
                                    Row(
                                      children: [
                                        GestureDetector(
                                          onTap: () {
                                            if (shoppingCartIsSelectedCopy[index].count <= 1) {
                                              EasyLoading.showToast("數量不能再少了");
                                              return;
                                            }
                                            ref
                                                .read(shoppingCartIsSelectProvide.notifier)
                                                .goodsCountMul(shoppingCartIsSelectedCopy[index].id);
                                            updateShoppingCartState({
                                              "selected": !shoppingCartIsSelectedCopy[index].selected,
                                              "count": shoppingCartIsSelectedCopy[index].count - 1,
                                              "id": shoppingCartIsSelectedCopy[index].skuId
                                            });

                                            ref
                                                .watch(shoppingCartGoodsTotalCount.notifier)
                                                .update((value) => value -= 1);
                                          },
                                          child: const Icon(Icons.remove),
                                        ),
                                        Container(
                                          width: 50,
                                          height: 20,
                                          alignment: Alignment.center,
                                          decoration: const BoxDecoration(color: Color.fromARGB(255, 234, 234, 234)),
                                          child: Text('${shoppingCartIsSelectedCopy[index].count}'),
                                        ),
                                        GestureDetector(
                                          onTap: () {
                                            ref
                                                .read(shoppingCartIsSelectProvide.notifier)
                                                .goodsCountAdd(shoppingCartIsSelectedCopy[index].id);
                                            updateShoppingCartState({
                                              "selected": !shoppingCartIsSelectedCopy[index].selected,
                                              "count": shoppingCartIsSelectedCopy[index].count + 1,
                                              "id": shoppingCartIsSelectedCopy[index].skuId
                                            });
                                            ref
                                                .watch(shoppingCartGoodsTotalCount.notifier)
                                                .update((value) => value += 1);
                                          },
                                          child: const Icon(Icons.add),
                                        ),
                                      ],
                                    )
                                  ],
                                )
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
                separatorBuilder: (BuildContext context, int index) {
                  return const SizedBox(height: 10);
                },
              );
            } else {
              return Column(
                children: [
                  Image.asset(
                    "assets/gouwuchekong.png",
                    width: 200,
                    height: 200,
                  ),
                  const Text(
                    "購物車是空的",
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey,
                    ),
                  ),
                  TextButton(
                    onPressed: () {
                      Beamer.of(context).beamToNamed('/');
                    },
                    child: Container(
                      width: 100,
                      height: 40,
                      decoration: const BoxDecoration(color: Colors.teal),
                      child: const Center(
                        child: Text(
                          "去逛逛",
                          style: TextStyle(fontSize: 16, color: Colors.white),
                        ),
                      ),
                    ),
                  ),
                ],
              );
            }
          },
        ),
      ],
    );
  }
}
